import { getConstructor, PEShadowElement, register } from 'element/share/element'

import PEAreaElementShadowHTML from '-!html-loader!./shadow.html'
import PEAreaElementShadowCSS from '-!to-string-loader!postcss-loader!sass-loader!./shadow.scss'
import { eachObject, EachReturn } from 'element/share/utils'
import { bind } from './modules/input'

function syncCss(shadow: ShadowRoot, constructor: CustomElementConstructor, nodeName: string) {
  console.log(constructor)
  const css = Reflect.get(constructor, 'GLOBAL_CSS') || ''
  const style = document.createElement('style')
  style.setAttribute(nodeName, '')
  style.textContent = css
  shadow.appendChild(style)
}

export default class PEAreaElement extends PEShadowElement {
  static nodeName = 'pe-area'

  public initialized = false

  #allowable: { [propName: string]: boolean } = { 'pe-line': false, 'pe-text': false }

  public get allowable() {
    return Object.keys(this.#allowable)
  }

  public set allowable(data) {
    data.forEach((nodeName) => {
      this.#allowable[nodeName] = false
    })
    this.register()
  }

  // constructor() {
  //   super()
  // }

  public register() {
    eachObject(this.#allowable, (status, nodeName) => {
      if (!status) {
        if (!this.query(`style[${nodeName}]`)) {
          getConstructor(nodeName)
            .then((constructor) => {
              syncCss(this.shadow, constructor, nodeName)
            })
            .catch((e) => {})
        }
        this.#allowable[nodeName] = true
      }
    })
  }

  public connected() {
    if (!this.initialized) {
      this.initialized = true
      this.shadow.innerHTML = `<style>${PEAreaElementShadowCSS}</style>${PEAreaElementShadowHTML}`
      this.register()
      bind(this)
    }
  }
}

register(PEAreaElement, [])
